package servlet;

import generateFile.BooksFile;
import generateFile.RecordsFile;
import generateFile.UsersFile;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.*;
import java.net.URLEncoder;

@WebServlet(name = "UploadServlet", value = "/UploadServlet")
public class UploadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String fileName=request.getParameter("fileName");
        if("用户名单.txt".equals(fileName)){
            UsersFile.generateUserList();
        }else if("书籍名单.txt".equals(fileName)){
            BooksFile.generateBookList();
        }else{
            RecordsFile.generateRecordList();
        }
        response.addHeader("content-Type","application/octet-stream");//任意文件类型
        //对文件名转码 防止乱码
        response.addHeader("content-Disposition","attachment,filename="+ URLEncoder.encode(fileName,"utf-8"));//文件名包括后缀
        String path="D:\\Documents\\Desktop\\材料\\IDEA_workspace\\webLibrarySystem\\fileList\\"+fileName;
        InputStream in=new FileInputStream(path);
        //产生一个输出流
        ServletOutputStream out= response.getOutputStream();
        byte[] bs=new byte[10];
        int readCount=-1;
        while((readCount=in.read(bs))!=-1){
            out.write(bs,0,readCount);
        }
        out.flush();
        out.close();
        in.close();
        System.out.println("下载成功！");
    }
}
